package com.rxt.util;

import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.UUID;

public class JwtUtils {
    //有效时长 -- 24小时
    private static final long EXPIRATION = 1000 * 60 * 60 * 24;
//    private static final long EXPIRATION = 1000 * 60;
    // 签名密钥
    private static final String SIGN_KEY = "rongxiaotong";
    // Authorization 前缀
    public static final String BEARER = "Bearer ";

    public static final String TOKEN = "Authorization";

    /**
     * 生成用户的 token
     * @param userId 用户 id
     */
    public static String createToken(long userId) {
        Date now = new Date(System.currentTimeMillis());
        Date exp = new Date(now.getTime() + EXPIRATION);
        return Jwts.builder()
                .setId(UUID.randomUUID().toString()) // 唯一标识
                .setSubject("AUTH-USER") // 签发人
                .setIssuedAt(now) // 签发时间
                .setExpiration(exp) //有效时间
                .claim("userId", userId) // 负载信息
                .signWith(SignatureAlgorithm.HS512, SIGN_KEY) // 加密算法
                .compressWith(CompressionCodecs.GZIP) // 字符串压缩
                .compact();
    }

    /**
     * 生成用户的 token
     * @param username 用户 username
     */
    public static String createToken(String username) {
        Date now = new Date(System.currentTimeMillis());
        Date exp = new Date(now.getTime() + EXPIRATION);
        return Jwts.builder()
                .setId(UUID.randomUUID().toString()) // 唯一标识
                .setSubject("AUTH-USER") // 签发人
                .setIssuedAt(now) // 签发时间
                .setExpiration(exp) //有效时间
                .claim("username", username) // 负载信息
                .signWith(SignatureAlgorithm.HS512, SIGN_KEY) // 加密算法
                .compressWith(CompressionCodecs.GZIP) // 字符串压缩
                .compact();
    }

    /**
     * 获取 token 中的负载信息
     * @param attrName 负载信息的 key 值
     * @param token token
     */
    public static Object get(String attrName, String token) {
        if (StrUtil.isEmptyIfStr(token)) return null;
        Claims claims = Jwts.parser().setSigningKey(SIGN_KEY).parseClaimsJws(token).getBody();
        return claims.get(attrName);
    }

    public static void main(String[] args) {
        System.out.println(createToken("zzw"));
        String token = "eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWyirJVLJSMjdLNjKyMEnRTTY0NNA1MUg20E1KSjXSTbNMNbJMNTUzsDAwVNJRKi5NAip2DA3x0A0Ndg0CimQmlihZGZpZGptbmhqbGukopVYUQAQsLAzNQQKlxalFeYm5qUCNVVXlSrUAemeBSHMAAAA.PqOXt-fwuYmSaxaBB6AT2p6n48pTHImbmLFIa6O0b_N2-Y2kxjTppYKPJffSkbzIOjCCR9_-zlxgX-KVmySdmA";
        System.out.println(get("username", token));
    }
}
